package com.jxwifi.cloud.quickclean.assemble;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.adapter.AssOrderAdapter;
import com.jxwifi.cloud.quickclean.adapter.PopAsswmAdapter;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.app.UrlPool;
import com.jxwifi.cloud.quickclean.bean.AssemRecordsBean;
import com.jxwifi.cloud.quickclean.bean.CollageRecordsBean;
import com.jxwifi.cloud.quickclean.model.AuzImpl;
import com.jxwifi.cloud.quickclean.okhttp.Params;
import com.jxwifi.cloud.quickclean.utils.shareUtils;
import com.jxwifi.cloud.quickclean.wxapi.WXEntryActivity;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.view.SuperSwipeRefreshLayout;

import java.util.List;

public class AssembleOrderPresenter {

    private String TAG = this.getClass().getSimpleName();

    private Context mContext;

    private AssembleOrderView mView;

    private AuzImpl mAuz;

    private AssOrderAdapter mAdapter;

    private IWXAPI mIWXAPI;

    private CollageRecordsBean mBeanList;

    private ProgressBar progressBar;
    private TextView textView;
    private ImageView imageView;
    private int mCurrentCounter;//获取的数据个数
    private int mPageIndex = 1;
    private int mTotalNum;//记录接口中的总条数（如果没有返回这个字段也可以不适用）
    private boolean isErr = true;



    public AssembleOrderPresenter(Context context,AssembleOrderView view){
        this.mContext=context;
        this.mView=view;
        this.mAuz=new AuzImpl();
    }

    public void initData(){  //CollageRecordsBean

        Params params = new Params();
        params.add("limit", mView.getLimit());
        params.add("page", mPageIndex);
        mAuz.auzget(UrlPool.COOLAGE_RECS, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                mBeanList= JSON.parseObject(data, CollageRecordsBean.class);
                mTotalNum = mBeanList.getTotal();
                Log.i(TAG,"mTotalNum = "+mTotalNum);
                //Log.i(TAG,"mBeanList.getSize = "+mBeanList.getSize());
                if (mBeanList.getSize()>0){
                    mView.getOrderList().setVisibility(View.VISIBLE);
                    mView.getListNull().setVisibility(View.GONE);
                    if (mPageIndex == 1){
                        setData(true, mBeanList.getRecords());
                    }else{
                        setData(false, mBeanList.getRecords());
                    }
                    //mAdapter.setNewData(mBeanList.getRecords());
                }else{
                    mView.getOrderList().setVisibility(View.GONE);
                    mView.getListNull().setVisibility(View.VISIBLE);
                    mView.getSwip().setEnabled(false);
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                isErr = false;
                mView.onFailure(errorCode, msg);
            }
        });
    }

    public void initView(){
        mView.getOrderList().setLayoutManager(new LinearLayoutManager(mContext));
        mView.getOrderList().setAdapter(mAdapter = new AssOrderAdapter(R.layout.assem_order_list_item));
        initData();
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    //分享
                    case R.id.tv_ass_order_item_share:
                        WeXinFen(mAdapter.getData().get(position).getOrderCode(),mAdapter.getData().get(position).getCdesk());
                        break;
                    //查看
                    case R.id.tv_ass_order_item_check:
                        Intent intent=new Intent();
                        intent.setClass(mContext, ADetailsActivity.class);
                        intent.putExtra("assemble_details", mAdapter.getData().get(position));
                        intent.putExtra("order_type", "start");
                        mContext.startActivity(intent);
                        break;
                }
            }
        });

        //上拉加载更多操作
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mView.getOrderList().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mCurrentCounter >= mTotalNum) {
                            //数据全部加载完毕
                            mAdapter.loadMoreEnd();
                        } else {
                            if (isErr) {
                                initData();
                                //成功获取更多数据
                                mCurrentCounter = mAdapter.getData().size();
                                mAdapter.loadMoreComplete();
                            } else {
                                //获取更多数据失败
                                isErr = true;
                                Toast.makeText(mContext, "获取更多数据失败", Toast.LENGTH_LONG).show();
                                mAdapter.loadMoreFail();
                            }
                        }
                    }
                }, 1500);

            }
        }, mView.getOrderList());

        mView.getSwip().setHeaderView(createHeaderView());
        mView.getSwip().setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

            @Override
            public void onRefresh() {
                textView.setText("正在刷新");
                imageView.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        mView.getSwip().setRefreshing(false);
                        progressBar.setVisibility(View.GONE);
                        mPageIndex = 1;
                        initData();
                    }
                }, 1000);
            }

            @Override
            public void onPullDistance(int distance) {
                // pull distance
            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "松开刷新" : "下拉刷新");
                imageView.setVisibility(View.VISIBLE);
                imageView.setRotation(enable ? 180 : 0);
            }
        });
    }

    public void WeXinFen(String orderCode,String cdesk){
        mIWXAPI = WXAPIFactory.createWXAPI(mContext, StateUtils.WX_APPID, false);
        mIWXAPI.registerApp(StateUtils.WX_APPID);
        shareUtils.share2weixin(mIWXAPI,1,mContext,6,orderCode,cdesk);
    }

    private View createHeaderView() {
        View headerView = LayoutInflater.from(mView.getSwip().getContext())
                .inflate(R.layout.layout_head, null);
        progressBar = (ProgressBar) headerView.findViewById(R.id.pb_view);
        textView = (TextView) headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        imageView = (ImageView) headerView.findViewById(R.id.image_view);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(R.drawable.down_arrow);
        progressBar.setVisibility(View.GONE);
        return headerView;
    }

    public void setData(boolean isRefresh, List data) {
        Log.i(TAG,"mPageIndex = "+mPageIndex);
        mPageIndex++;
        final int size = data == null ? 0 : data.size();

        if (isRefresh) {
            mView.getSwip().setEnabled(true);
            mAdapter.setNewData(data);

        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        mCurrentCounter = mAdapter.getData().size();
        if (size < mPageIndex) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }

}
